﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using DAL;
using Entity;

namespace BLL
{
    public class MessageBO
    {
        /// <summary>
        /// 插入消息;
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static int InsertMessage(Message msg)
        {
            return MessageDAO.InsertMessage(msg);
        }

        /// <summary>
        /// 获取未读消息列表;
        /// </summary>
        /// <param name="uid">User.Id</param>
        /// <returns></returns>
        public static List<Message> GetUnreadMessages(int uid)
        {
            DataTable dt = MessageDAO.GetUnreadMessages(uid);
            return ChangeMessageTableToList(dt);
        }

        /// <summary>
        /// 获取未读消息数;
        /// </summary>    
        public static int GetUnreadMsgNum(int uid)
        {
            int num = 0;
            DataTable dt = MessageDAO.GetUnreadMessages(uid);
            if (dt != null)
            {
                num = dt.Rows.Count;
            }
            return num;
        }

        /// <summary>
        /// 获取已读消息列表;
        /// </summary>     
        public static List<Message> GetReadMessages(int uid)
        {
            DataTable dt = MessageDAO.GetReadMessages(uid);
            return ChangeMessageTableToList(dt);
        }

        /// <summary>
        /// 将消息表格转为消息对象的列表;
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static List<Message> ChangeMessageTableToList(DataTable dt)
        {
            List<Message> messagesList = new List<Message>();

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Message message = new Message()
                    {
                        CreatTime = (DateTime)row["CreatTime"],
                        IsRead = (bool)row["IsRead"],
                        MessageContent = row["MessageContent"].ToString(),
                        MessageId = (int)row["MessageId"],
                        UserId = (int)row["UserId"]
                    };
                    messagesList.Add(message);
                }
            }

            return messagesList;
        }

        /// <summary>
        /// 更新消息的已/未读状态;
        /// </summary>
        /// <param name="message"></param>
        public static void UpdateMessageReadStatus(Message message)
        {
            MessageDAO.UpdateMessageReadStatus(message);
        }
    }
}
